package com.duanyu.mysecurity.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class KickOutController {
    @Autowired
    private SessionRegistry sessionRegistry;

    @GetMapping("/kickout")
    public void kickOut(String username){
        //查找在线的用户
        List<Object> allPrincipals = sessionRegistry.getAllPrincipals();
        for (Object principal:allPrincipals){
            UserDetails userDetail = (UserDetails) principal;
            if (username.equals(userDetail.getUsername())){
                //如果参数传来的username等于userDetail中的username，则是要踢出的用户
                //找到该用户的session，不包含过期会话
                List<SessionInformation> allSessions = sessionRegistry.getAllSessions(userDetail, false);
                if (null!=allSessions&&!allSessions.isEmpty()){
                    //遍历该用户的会话，使其失效
                    for (SessionInformation session:allSessions){
                        session.expireNow();
                    }
                }
            }
        }
    }
}
